package com.czkevin.cifjiaocheng.cef;

import de.tr7zw.nbtapi.NBTCompound;
import com.czkevin.cef.entities.base.BaseCustomEntity;
import com.czkevin.cif.CIFItemInstance;
import com.czkevin.cif.CustomItemFramework;
import com.czkevin.cif.ItemRegister;
import com.czkevin.cifjiaocheng.ShitTNT;
import org.bukkit.Location;
import org.bukkit.Particle;
import org.bukkit.SoundCategory;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.LivingEntity;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.util.EulerAngle;

import java.util.Random;

public class ShitTNTEntity extends BaseCustomEntity {
    public static final String TYPE = "ShitTNTEntity";

    private static final Random RANDOM = new Random();

    private static float randomPitch() {
        return 1.0f + (RANDOM.nextBoolean() ? 1f : -1f) * (RANDOM.nextFloat() * 0.2f);
    }

    /**
     * 用这个变量记录已经过去了几个tick
     */
    private long elapsedTicks = 0L;

    @Override
    protected void _setup(ArmorStand armorStand, NBTCompound nbtCompound) {
        armorStand.setGravity(true);
        armorStand.setHeadPose(new EulerAngle(
            Math.toRadians(-45), 0d, 0d
        ));
        armorStand.getEquipment().setHelmet(
            ItemRegister.get("ShitTNT").generateItemStack(null, false)
        );
        if(nbtCompound != null) {
            elapsedTicks = nbtCompound.getLong("elapsed_ticks");
        }
    }

    @Override
    protected void _preUpdate(boolean force) {
        elapsedTicks ++;
        if(elapsedTicks > 20*10) {
            // 5秒，爆炸。释放恶臭！
            playSound("jiaocheng.echou_long");

            igniteCloseTNT();

            Location location = getLocation();
            location.getWorld().spawnParticle(
                Particle.EXPLOSION_HUGE,
                location, 2,
                RANDOM.nextDouble() * 0.1d,
                RANDOM.nextDouble() * 0.1d,
                RANDOM.nextDouble() * 0.1d,
                RANDOM.nextDouble() * 0.1d
            );

            location.getWorld().getNearbyEntities(
                location, 10d, 4d, 10d
            ).stream().filter(f -> LivingEntity.class.isAssignableFrom(f.getClass()))
                .forEach(l -> {
                    LivingEntity living = (LivingEntity) l;
                    // 增加眩晕效果
                    living.addPotionEffect(
                        new PotionEffect(
                            PotionEffectType.CONFUSION,
                            400,
                            100
                        )
                    );
                    // 增加中毒效果
                    living.addPotionEffect(
                        new PotionEffect(
                            PotionEffectType.WITHER,
                            400,
                            4
                        )
                    );
                    // 增加缓慢效果
                    living.addPotionEffect(
                        new PotionEffect(
                            PotionEffectType.SLOW,
                            400,
                            10
                        )
                    );
                    // 增加致盲效果
                    living.addPotionEffect(
                        new PotionEffect(
                            PotionEffectType.BLINDNESS,
                            400,
                            10
                        )
                    );
                });
            getBukkitEntity().remove();
        } else {
            if(elapsedTicks % 2 == 0) {
                Location loc = getLocation();
                loc.getWorld().spawnParticle(
                    Particle.SMOKE_LARGE,
                    loc,
                    2,
                    (RANDOM.nextBoolean() ? 1d : -1d) * RANDOM.nextDouble() * .2d,
                    RANDOM.nextDouble() * .2d,
                    (RANDOM.nextBoolean() ? 1d : -1d) * RANDOM.nextDouble() * .2d
                );
            }
            // 百分号就是求余数 10 % 3 的结果就是 1 因为10除3余1
            // 20 个 tick 是一秒
            if(elapsedTicks < 20*5 && elapsedTicks % 20 == 0) {
                // 前五秒钟每一秒发出一次恶臭
                playShit();
            } else if(elapsedTicks >= 20*5 && elapsedTicks < 20*7 && elapsedTicks % 10 == 0) {
                // 5-7秒每半秒钟恶臭一次
                playShit();
            } else if (elapsedTicks >= 20*7 && elapsedTicks % 5 == 0) {
                playShit();
            }
         }
    }

    /**
     * 引燃附近的恶臭TNT
     */
    private void igniteCloseTNT() {
        Location location = getLocation();
        World world = location.getWorld();
        int bx = location.getBlockX();
        int by = location.getBlockY();
        int bz = location.getBlockZ();
        for(int x = bx - 2; x <= bx + 2; x ++) {
            for(int y = by - 2; y <= by + 2; y ++) {
                for(int z = bz - 2; z <= bz + 2; z ++) {
                    if(x == bx && y == by && z == bz) continue;
                    Block block = world.getBlockAt(x, y, z);
                    CIFItemInstance instance = CustomItemFramework.getCIFDataFromBlock(block);
                    if(instance != null && ShitTNT.class.isAssignableFrom(instance.type.getClass())) {
                        // 这是个恶臭TNT，尝试引爆！！！
                        ((ShitTNT) instance.type).ignite(block);
                    }
                }
            }
        }
    }

    /**
     * 发出恶臭
     */
    private void playShit() {
        playSound("jiaocheng.heng.random");
    }

    private void playSound(String name) {
        Location location = getLocation();
        location.getWorld().playSound(
            location, name,
            SoundCategory.AMBIENT,
            1.0f,
            randomPitch()
        );
    }

    @Override
    public void _preUnload() {
        getData().setLong("elapsed_ticks", elapsedTicks);
    }

    @Override
    public String getType() {
        return TYPE;
    }
}
